//
//  UserVoiceViewController.m
//  Molian
//
//  Created by wansong on 4/25/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "UserVoiceViewController.h"

#import "VoiceCell.h"
#import "VoiceRecordViewController.h"

#import "UIViewController+MJPopupViewController.h"

#import "MLAudioPlayer.h"
#import "AmrPlayerReader.h"
#import "MLAudioMeterObserver.h"

@interface UserVoiceViewController ()

@property (nonatomic,strong) NSArray *tags;;

@property (strong, nonatomic) WWTagsCloudView* tagsCloud;
@property (strong, nonatomic) UITableView *tableView;


@property (nonatomic, strong) MLAudioPlayer *player;
@property (nonatomic, strong) AmrPlayerReader *amrReader;

@property NSInteger voicePlayIndex;

@property NSInteger voicePlayStatus;
@property (nonatomic, strong)UILabel *hintLabel;

// 共享的音频播放计时器
@property (nonatomic, strong) NSTimer *updateAudioUITimer;

@end

@implementation UserVoiceViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.voiceArray.count == 0) {
         self.hintLabel.hidden = NO;
    }else{
         self.hintLabel.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"声线";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, DeviceWidth, 220)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    // 提示文字
    UILabel *placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 90, 64, 40)];
    placeholderLabel.text = @"我的声线:";
    placeholderLabel.font = [UIFont fontWithName:FontName size:14];
    placeholderLabel.textColor = [UIColor lightGrayColor];
    [self.view addSubview:placeholderLabel];
    // 提示文字
    self.hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(20+64, 90, DeviceWidth-64-20, 40)];
    self.hintLabel.text = @"唱一首歌、讲个段子或者介绍一下自己";
    self.hintLabel.font = [UIFont fontWithName:FontName size:12];
    self.hintLabel.textColor = [UIColor lightGrayColor];
    self.hintLabel.hidden = YES;
    [self.view addSubview:self.hintLabel];
    
    
    //登陆按钮
    BFPaperButton *add = [[BFPaperButton alloc]initWithFrame:CGRectMake((DeviceWidth-170)/2, 360, 170, 45)raised:NO];
    [add setTitle:@"添加声线" forState:UIControlStateNormal];
    [add setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    add.layer.masksToBounds = YES;//开启圆角
    [add setBackgroundImage:[UIImage imageWithColor:APPCOLOR(1)] forState:UIControlStateNormal];
    [add.layer setCornerRadius:CGRectGetHeight([add bounds]) / 2];
    add.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [add addTarget:self action:@selector(tagClickAtIndex) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:add];
    
    // 初始化音频播放器
    [self initAudioReader];
    
    // 监听保存了新的声线
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newVoiceNoti) name:NOTIFICATION_TYPE_NEW_VOICE object:nil];
    if (self.voiceArray.count >1) {
        [self deleteqbu];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.voiceArray.count == 0) {
        self.hintLabel.hidden = NO;
    }else{
        self.hintLabel.hidden = YES;
    }
    static  NSString *CellIdentifier = @"VoiceCell" ;
    VoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[VoiceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        
    }
    NSLog(@"self.voiceArray===%@",self.voiceArray);
    MLVoice *voice = self.voiceArray[indexPath.row];
    // 显示删除按钮
    [cell.delBtn setHidden:NO];
    [cell.delBtn addTarget:self action:@selector(deleteVoice:) forControlEvents:UIControlEventTouchUpInside];
    cell.delBtn.tag = indexPath.row;
    [cell.voiceBtn setTitle:[NSString stringWithFormat:@"%ld\"",(long)voice.time] forState:UIControlStateNormal];
    [cell.voiceBtn addTarget:self action:@selector(playVoice:) forControlEvents:UIControlEventTouchUpInside];
    cell.voiceBtn.tag = indexPath.row;

    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.voiceArray.count >= 1) {
        return 1;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

#pragma mark - tag delegate
- (void)tagClickAtIndex{
    // 个数限制1个
    if ([self.voiceArray count] >= 1) {
//        [HUD Prompt:@"最多只能添加三个"];
         [HUD Prompt:@"最多只能添加一个"];
        return;
    }
    // 选择tag的代理
    VoiceRecordViewController *recorderView = [[VoiceRecordViewController alloc]init];
    recorderView.voiceArray = self.voiceArray;
    recorderView.voiceFileArray = self.voiceFileArray;
//    recorderView.voiceTheme = self.tags[tagIndex];
    [self presentPopupViewController:recorderView animationType:MJPopupViewAnimationSlideTopBottom];
}

#pragma mark - notification 

- (void)newVoiceNoti {
    if ([self.delegate respondsToSelector:@selector(changeVoice)]) {
        [self.delegate changeVoice];
    }
    
    // 刷新声线列表显示
    [self.tableView reloadData];
}

#pragma mark - private method

- (void)deleteVoice: (UIButton *)sender {
    // 删除
    MLVoice *voice = self.voiceArray[sender.tag];
    [voice deleteInBackground];
    if (self.voiceFileArray&&self.voiceFileArray.count) {
        [self.voiceFileArray removeObjectAtIndex:sender.tag];
    }
    if (self.voiceArray&&self.voiceArray.count) {
        [self.voiceArray removeObjectAtIndex:sender.tag];

    }
    [self.tableView reloadData];
    
    if (self.voiceArray.count == 0) {
        [MLUser currentUser].isHasVoice = NO;
        [[MLUser currentUser] saveInBackground];
    }
}

-(void)deleteqbu
{
    for (int i = 1; i< self.voiceArray.count; i++) {
        // 删除
        MLVoice *voice = self.voiceArray[i];
        [voice deleteInBackground];
        if (self.voiceFileArray&&self.voiceFileArray.count) {
            [self.voiceFileArray removeObjectAtIndex:i];
        }
        if (self.voiceArray&&self.voiceArray.count) {
            [self.voiceArray removeObjectAtIndex:i];
            
        }
        [self.tableView reloadData];
        
        if (self.voiceArray.count == 0) {
            [MLUser currentUser].isHasVoice = NO;
            [[MLUser currentUser] saveInBackground];
        }
    }
   
    
}

#pragma mark - audio play

- (void)initAudioReader {
    // 初始化音频播放器
    MLAudioPlayer *player = [[MLAudioPlayer alloc]init];
    AmrPlayerReader *amrReader = [[AmrPlayerReader alloc]init];
    player.fileReaderDelegate = amrReader;
    
    self.player = player;
    self.amrReader = amrReader;
    
}

- (void)playVoice:(UIButton *)sender {
    if ([self.player isPlaying]) {
        [self.player stopPlaying];
        
        // 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
        
        [sender setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
    }
    self.amrReader.filePath = self.voiceFileArray[sender.tag];
    self.voicePlayIndex = sender.tag;
    self.voicePlayStatus = 3;
    [self.player startPlaying];
    self.updateAudioUITimer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(updateVoiceBtnUI) userInfo:nil repeats:YES];
}

- (void)updateVoiceBtnUI {
    // 更新播放按钮显示
    VoiceCell *cell = (VoiceCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.voicePlayIndex inSection:0]];
    if ([self.player isPlaying]) {
        // 更新图片显示
        if (3 == self.voicePlayStatus) {
            self.voicePlayStatus = 1;
        } else {
            self.voicePlayStatus++;
        }
        NSString *bgImgName = [NSString stringWithFormat:@"voice_play_%ld", (long)self.voicePlayStatus];
        [cell.voiceBtn setImage:[UIImage imageNamed:bgImgName] forState:UIControlStateNormal];
    } else {
        // 播放结束, 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
        [cell.voiceBtn setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
    }
}
- (void)dealloc
{
    self.delegate = nil;
}
@end
